<?php
class TaskSearchController  extends Zone_Action{
	public function initAction(){
		if(!$this->hasRole('task')){
			$this->setContent(error('Bạn không được phép truy cập phân hệ này'));	
			$this->stop();
		}
		$this->set('types',$this->Model->fetchAll("SELECT * FROM `tasks_types` ORDER BY `title`"));	
	}		
	
	public function formAction(){}

	/* Search advance */
	public function indexAction(){		
		$user_id = get_user_id();
		$vars = array();
	
		$order_by = "ORDER BY `a`.`date_created` DESC";
		
		$current_page = max(getInt('p',1),1);		
		$range_page = max(10,(int)$this->getConfig('user.page',20));
		
		if( isset($_REQUEST['p']) ){
			$vars['p'] = $current_page;
		}
		
		if( isset($_REQUEST['rp'])){
			$vars['rp'] = $range_page;
		}
		
		$limit = "LIMIT ".($current_page-1)*$range_page.",$range_page";
				
		$field_order = array('title','project_id','rate','status','date_start','date_end');
		foreach( $field_order as $f ){
			if( get('order_by') == $f ){
				$order_by = "ORDER BY $f ". ( get('order_type') == 'desc' ? 'desc' : 'asc');
				$vars['order_by'] = $f;
				if( get('order_type') == 'desc' ){
					$vars['order_by']='desc';
				}
				break;	
			}	
		}		
		
		$where = array();
		
		$where[] = "`a`.`is_draft`='no'";
		$where[] = "( `c`.`user_id`='$user_id' OR `a`.`created_by_id`='$user_id' )";

		//apply every field
		if( get('s','') != '' ){
			$s=get('s','');
			$vars['s'] = $s;
			if( get('ct','') == 'yes' ){
				$where[] ="( UPPER(`a`.`title`) LIKE UPPER('%$s%') OR UPPER(`a`.`desc`) LIKE UPPER('%$s%') )";		
				$vars['ct'] = 'yes';				
			}else{
				$where[] ="UPPER(`a`.`title`) LIKE UPPER('%$s%')";		
			}	
		}	
		
		//apply every field
		if( get('status_min',0) != 0 ){
			$s=get('status_min',0);
			$vars['status_min'] = $s;
			$where[] ="`a`.`status` >= '$s'";		
		}			

		//apply every field
		if( get('status_max',0) != 0 ){
			$s=get('status_max',0);
			$vars['status_max'] = $s;
			$where[] ="`a`.`status` <= '$s'";		
		}			
		
		//search with catelogeries
		$types = get('type',array(),true);
		if( count($types) > 0 ){
			$x=array();
			foreach( $types as $j => $i ){
				$vars["type[$j]"] = $i;
				$x[] = "'$i'";
			}
			$where[] ="`a`.`parent_id` IN (".implode(',',$x).")";
		}
		
		//search with user implements
		$users = get('users',array(),true);
		if( count($users) > 0 ){
			$x=array();
			foreach( $users as $j => $i ){
				$vars["users[$j]"] = $i;
				$x[] = "'$i'";
			}
			$where[] =" EXISTS( SELECT `t`.`ID` FROM `tasks_users` as t 
				WHERE `t`.`task_id`=`a`.`ID` 
				AND `t`.`is_implement`='yes' AND `t`.`user_id` IN (".implode(',',$x).") )";
		}

		//search with user implements
		$users = get('assigns',array(),true);
		if( count($users) > 0 ){
			$x=array();
			foreach( $users as $j => $i ){
				$vars["assigns[$j]"] = $i;
				$x[] = "'$i'";
			}
			$where[] =" `a`.`created_by_id` IN (".implode(',',$x).")";
		}		
	
		if( get('date_start','') != '' ){
			$date_start = get('date_start','');
			$vars['date_start'] = $date_start;
			
			if( get('time_start','') != '' ){
				$time_start = get('time_start','');
				$where[] = "`a`.`date_start` >= '$time_start:00 ".change_date_format($date_start)."'";
				$vars['time_start'] = $time_start;
			}else{
				$where[] = " CAST(`a`.`date_start` as DATE ) >= '".change_date_format($date_start)."'";
			}			
		}

		if( get('date_end','') != '' ){
			$date_end = get('date_end','');
			$vars['date_end'] = $date_end;
			
			if( get('time_end','') != '' ){
				$time_end = get('time_end','');
				$where[] = "`a`.`date_end` <= '$time_end:00 ".change_date_format($date_end)."'";
				$vars['time_end'] = $time_end;
			}else{
				$where[] = " CAST(`a`.`date_end` as DATE ) <= '".change_date_format($date_end)."'";
			}			
		}

		if( get('status','all') != 'all' ){
			$where[] = "`a`.`status`='".get('status','')."'";
			$vars['status'] = get('status','');
		}

		if( get('file','') == 'yes' ){
			$where[] = "EXISTS( SELECT `f`.`ID` 
				FROM `tasks_files` as `f`
				WHERE `f`.`task_id`=`a`.`ID` LIMIT 1 )";
			$vars['file'] = 'yes';
		}
		
		if( count($where) < 3 ){
			return $this->setJSON(array(
				alert	=> 'Chưa có từ khóa tìm kiếm'
			));
		}		
		
		$where = implode(' AND ',$where);
			
		$sql = "FROM  `tasks` as `a`
			LEFT JOIN `users` as `u`
				ON `a`.`created_by_id`=`u`.`ID`
			LEFT JOIN `tasks_reads` as `b`
				ON `b`.`task_id`=`a`.`ID` AND `b`.`user_id`='$user_id'				
			LEFT JOIN `tasks_users` as `c`
				ON `c`.`user_id`='$user_id' AND `c`.`task_id`=`a`.`ID`
			LEFT JOIN `projects` as `d`
				ON `d`.`ID`=`a`.`project_id`
			WHERE $where ";
		
		$total = $this
			->Model
			->fetchOne("SELECT COUNT(*) as `total` $sql");
				
		$posts = $this->Model->fetchAll("SELECT `a`.*,
				IF(`b`.`task_id` IS NOT NULL AND `b`.`date_active` >= `a`.`date_active`,'yes','no') as `is_read`,
				`d`.`title` as `project_title`,
				`u`.`username` as `created_by_name`,	
				`u`.`is_deleted` as `created_is_deleted`	
			$sql $order_by $limit");
		$a = $vars;
		unset($a['p']);
		
		$page = page_ajax('#Task/Search?'.to_query_configs($a).'&p=', $total , $range_page, $current_page);	
			
		$this->set(array(
			page	=> $page,
			total	=> $total,
			vars	=> $vars,
			posts	=> $posts
		));			
	}	
}	